/*
   @Copyright:LintCode
   @Author:   tjyemail
   @Problem:  http://www.lintcode.com/problem/spiral-matrix
   @Language: C++
   @Datetime: 16-02-09 08:37
   */

class Solution {
public:
	/**
	 * @param matrix a matrix of m x n elements
	 * @return an integer array
	 */
	vector<int> spiralOrder(vector<vector<int> > &mat) {
		// Write your code here
		if (mat.size()<1 || mat[0].size()<1) return {};
		vector<int> vs(mat.size()*mat[0].size(),0);
		for(int l=0, r=mat[0].size()-1, t=0, b=mat.size()-1, c=0;
			l<=r && t<=b; ++l,--r,++t,--b){
			for (int i=l; i<=r; vs[c++]=mat[t][i++]);
			for (int i=t+1; i<b; vs[c++]=mat[i++][r]);
			for (int i=r; i>=l && t<b; vs[c++]=mat[b][i--]);
			for (int i=b-1; i>t && l<r; vs[c++]=mat[i--][l]);
		}
		return vs;
	}
};
